package com.bw.controller;

import cn.hutool.crypto.digest.DigestUtil;
import com.bw.domain.Mecicu;
import com.bw.service.MecicuService;
import com.bw.service.SysUserService;
import com.bw.utils.common.JWTUtils;
import com.bw.utils.common.Result;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;

@RequestMapping("/mecu")
@RestController
public class MecuController {
    @Autowired
    MecicuService mecicuService;
    @Resource
    RedisTemplate redisTemplate;
    @Autowired
    SysUserService sysUserService;
    @RequestMapping("/list")
    public Result list(@RequestParam(defaultValue = "")Integer pageNum,String name){
        //开启分页
        PageHelper.startPage(pageNum,3);
        List<Mecicu> mecicus = mecicuService.list1(name);
        return Result.success(new PageInfo<>(mecicus));
    }
    @PreAuthorize("hasRole('ADMIN')")
    @RequestMapping("/add")
    public Result add(@RequestBody Mecicu mecicu){
//        String username = JWTUtils.getUsername();
//        String listshtu = sysUserService.listshtu(username);
//        if(!"admin".equals(listshtu)){
//            return  Result.fail("权限不足");
//        }else{
            String s = DigestUtil.md5Hex(mecicu.toString());
            Boolean aBoolean = redisTemplate.opsForValue().setIfAbsent(s, 1, 5, TimeUnit.MINUTES);
            if(aBoolean){
                boolean save = mecicuService.save(mecicu);
                return save?Result.success():Result.fail();
            }else{
                return  Result.fail("表单重复提交");
            }
//        }


    }
}
